package com.ruoyi.web.controller.business.order.factory;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ruoyi.business.base.PageParam;
import com.ruoyi.business.order.domain.JbApprovalLog;
import com.ruoyi.business.order.domain.JbOrder;
import com.ruoyi.business.order.domain.JbPaymentReceived;
import com.ruoyi.business.order.domain.JbRefund;
import com.ruoyi.business.order.service.JbApprovalLogService;
import com.ruoyi.business.order.service.JbOrderService;
import com.ruoyi.business.order.service.JbPaymentReceivedService;
import com.ruoyi.business.order.service.JbRefundService;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.system.service.ISysDictTypeService;
import com.ruoyi.web.controller.business.order.vo.JbAuditVO;
import com.ruoyi.web.controller.business.order.vo.JbOrderStatusEnum;
import com.ruoyi.web.controller.flyflow.factory.FlyFlowFactory;
import com.ruoyi.web.core.JoController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 审批日志
 *
 * @author Jyl
 */
@Component
public class JbApprovalLogFactory extends JoController
{

    @Autowired
    private JbApprovalLogService jbApprovalLogService;

    @Autowired
    private ISysDictTypeService sysDictTypeService;

    @Autowired
    private FlyFlowFactory flyFlowFactory;

    @Autowired
    private JbOrderService jbOrderService;

    @Autowired
    private JbRefundService jbRefundService;

    @Autowired
    private JbPaymentReceivedService jbPaymentReceivedService;

    /**
     * 查询审批日志（针对订单、退款等各个状态操作记录）列表
     */
    public IPage<JbApprovalLog> list(PageParam page, JbApprovalLog jbApprovalLog)
    {
        LambdaQueryWrapper<JbApprovalLog> select = new LambdaQueryWrapper<>();
        select.eq(JbApprovalLog::getOrderNumber, jbApprovalLog.getOrderNumber())
                .orderByDesc(JbApprovalLog::getCreateTime)
        ;

        IPage<JbApprovalLog> iPage = jbApprovalLogService.page(page.b(), select);
        return iPage;
    }

    /**
     * 添加日志
     *
     * @param logType   审批类型
     * @param bizNumber 业务订单信息
     * @param processId 流程实例id
     * @param node      节点名称
     * @param content   操作内容
     * @param result    操作结果
     */
    public void saveApprovalLog(String logType, String bizNumber, String processId, String node, String content,
                                String result)
    {
        JbApprovalLog jbApprovalLog = new JbApprovalLog();
        jbApprovalLog.setLogType(logType);//日志类型
        jbApprovalLog.setOrderNumber(bizNumber);//业务编号
        jbApprovalLog.setTime(new Date());//时间
        jbApprovalLog.setNode(node);//节点

        jbApprovalLog.setOperator(getNickName());//操作人
        jbApprovalLog.setOperatorId(getUserId());//操作人主键
        jbApprovalLog.setOperationContent(content);//操作内容
        jbApprovalLog.setOperationResult(result);//操作结果
        jbApprovalLog.setProcessId(processId);//流程主键

        jbApprovalLogService.save(jbApprovalLog);
    }

    /**
     * 订单状态
     *
     * @param jbAuditVO
     * @return
     */
    public boolean updateOrder(JbAuditVO jbAuditVO)
    {
        String status = "";

        if (jbAuditVO.getFlyflow().getBoolean("approveResult"))
        {
            status = switch (jbAuditVO.getTaskName())
            {
                case "业务审批" -> JbOrderStatusEnum.task2_1.getKey();
                case "主管审批" -> JbOrderStatusEnum.task2_1.getKey();
                case "领导审批" -> JbOrderStatusEnum.task2_1.getKey();
                case "财务审批" -> JbOrderStatusEnum.task8.getKey();
                default -> "";
            };
        } else
        {
            status = JbOrderStatusEnum.task5.getKey();
        }

        LambdaUpdateWrapper<JbOrder> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(JbOrder::getOrderNumber, jbAuditVO.getProcessInstanceBizCode())
                .set(JbOrder::getOrderStatus, status);
        return jbOrderService.update(updateWrapper);
    }

    /**
     * 退换货状态
     *
     * @param jbAuditVO
     * @return
     */
    public boolean updateRefund(JbAuditVO jbAuditVO)
    {
        String status = "";

        if (jbAuditVO.getFlyflow().getBoolean("approveResult"))
        {
            status = switch (jbAuditVO.getTaskName())
            {
                case "一级审批" -> JbOrderStatusEnum.task2_1.getKey();
                case "二级审批" -> JbOrderStatusEnum.task2_1.getKey();
                case "三级审批" -> JbOrderStatusEnum.task2_1.getKey();
                case "四级审批" -> JbOrderStatusEnum.task1.getKey();
                default -> "";
            };
        } else
        {
            status = JbOrderStatusEnum.task5.getKey();
        }

        LambdaUpdateWrapper<JbRefund> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(JbRefund::getRefundNumber, jbAuditVO.getProcessInstanceBizCode())
                .set(JbRefund::getApprovalStatus, status);
        return jbRefundService.update(updateWrapper);
    }

    /**
     * 回款状态
     *
     * @param jbAuditVO
     * @return
     */
    public boolean updatePaymentReceived(JbAuditVO jbAuditVO)
    {
        String status = "";

        if (jbAuditVO.getFlyflow().getBoolean("approveResult"))
        {
            status = switch (jbAuditVO.getTaskName())
            {
                case "审批人" -> JbOrderStatusEnum.task1.getKey();
                default -> "";
            };
        } else
        {
            status = JbOrderStatusEnum.task5.getKey();
        }

        LambdaUpdateWrapper<JbPaymentReceived> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(JbPaymentReceived::getPaymentNumber, jbAuditVO.getProcessInstanceBizCode())
                .set(JbPaymentReceived::getStatus, status);
        return jbPaymentReceivedService.update(updateWrapper);
    }

    /**
     * 审批 状态变更
     *
     * @param type      业务类型
     * @param jbAuditVO
     * @return
     */
    public boolean fnStatus(String type, JbAuditVO jbAuditVO)
    {
        switch (type)
        {
            case "order" -> updateOrder(jbAuditVO);
            case "refund" -> updateRefund(jbAuditVO);
            case "payment_received" -> updatePaymentReceived(jbAuditVO);
        }
        return true;
    }

    /**
     * 审批业务
     *
     * @param jbAuditVO
     * @return
     */
    @Transactional
    public boolean audit(JbAuditVO jbAuditVO)
    {
        List<SysDictData> list = sysDictTypeService.selectDictDataByType("bus_form_type");
        Map<String, String> dict = list.stream().collect(Collectors.toMap(
                SysDictData::getDictLabel,
                SysDictData::getDictValue));

        flyFlowFactory.sendTak(jbAuditVO.getFlyflow());

        saveApprovalLog(
                dict.get(jbAuditVO.getProcessName()),
                jbAuditVO.getProcessInstanceBizCode(),
                jbAuditVO.getProcessInstanceId(),
                jbAuditVO.getTaskName(),
                jbAuditVO.getTaskName(),
                jbAuditVO.getFlyflow().getBoolean("approveResult") ? "通过" : "驳回"
        );

        fnStatus(dict.get(jbAuditVO.getProcessName()), jbAuditVO);
        return true;
    }

    public boolean fnTaskName(String taskName)
    {
        return true;
    }
}
